import router from '@/router';
import { ElMessage } from 'element-plus';
import useStore from '@/store';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { json } from 'stream/consumers';
NProgress.configure({ showSpinner: false }); // 进度环显示/隐藏

// 白名单路由
const whiteList = ['/login', '/404', '/401', '/403'/*,"/dashboard","/codegen"*/];

router.beforeEach(async (to, from, next) => {
	NProgress.start();
	const { user, permission } = useStore();
	const hasToken = user.token;
	if (hasToken) {
		// 登录成功，跳转到首页
		if (to.path === '/login') {
			next({ path: '/' });
			NProgress.done();
		} else {
			const hasGetUserInfo = user.roles.length > 0;		
			//本地有角色
			if (hasGetUserInfo) {						
				//console.log("有"+JSON.stringify(to))
				if (to.matched.length === 0) {
					from.name ? next({ name: from.name }) : next('/401');
				} else {
					next();
				} 
			} else {				
				try {					
					//获取用户信息,开发模式未登录成功不需要获取服务端信息	，登录成功也需要获取服务端信息				
					//if (hasToken != "dev") {//获取服务端用户信息
					await user.getUserInfo(hasToken);
					const roles = user.roles;
					//} 					
					const accessRoutes: any = await permission.generateRoutes(roles);
					accessRoutes.forEach((route: any) => {
						//console.log(route) 
						router.addRoute(route);
					});
					next({ ...to, replace: true });
				} catch (error) {
					// 移除 token 并跳转登录页
					await user.resetToken();
					ElMessage.error((error as any) || 'Has Error');
					next(`/login?redirect=${to.path}`);
					NProgress.done();
				}
			}
		}
	} else {
		// 未登录可以访问白名单页面(登录页面)
		//var result = whiteList.find(item => { return to.path.indexOf(item) != -1; });
		//if (result) {
		if (whiteList.indexOf(to.path) !== -1) {
			next();
		} else {
			next(`/login?redirect=${to.path}`);
			NProgress.done();
		}
	}
});

router.afterEach(() => {
	NProgress.done();
});
